package top.kaoshanji.p2ch15b;

import java.util.concurrent.Callable;

/**
 * author kaoshanji
 * ^_^
 * create time 2025/2/24 17:57
 */
public class MyFutureExecutorDome {

    // 代码清单-p2ch15b-460页b：异步执行任务
    public <V> MyFuture<V> execute(final Callable<V> task) {

        final Object lock = new Object();
        final MyFutureExecuteThread<V> thread = new MyFutureExecuteThread<>(task, lock);
        thread.start();

        MyFuture<V> future = new MyFuture<V>() {

            @Override
            public V get() throws Exception {
                synchronized (lock) {
                    while (!thread.isDone()) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            /// ///
                        }
                    }

                    if (thread.getException() != null) {
                        throw thread.getException();
                    }

                    return thread.getResult();
                }
            }
        };

        return future;
    }

    // 代码清单-p2ch15b-459页b：异步调用示例
    public static void main(String[] args) {

        MyFutureExecutorDome execute = new MyFutureExecutorDome();

        // 子任务
        Callable<Integer> subTask = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                // ...执行异步任务
                int millis = (int) (Math.random() * 1000);
                Thread.sleep(millis);
                return millis;
            }
        };

        // 异步调用，返回一个 MyFuture 对象
        MyFuture<Integer> future = execute.execute(subTask);

        // ... 执行其他操作
        try {
            // 获取异步调用的结果
            Integer result = future.get();
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }



}
